// @ts-nocheck
import { isNumber } from '@src/util/type';
import {
  FORM_FIELD_TEXT_MAX_LENGTH,
  FORM_FIELD_TEXTAREA_MAX_LENGTH
} from '@src/model/const/Number.ts';
/* utils */
import { isFunction } from '@src/util/type'
/* form */
import { FormFieldMap } from '@src/mform/components';

import FormField from '../MFormField'
export * from './validate.tsx';

import { cloneDeep } from 'lodash'

import Vue from 'vue'

const DEFAULT_PLACEHOLDER = {
  text: `最多${FORM_FIELD_TEXT_MAX_LENGTH}字`,
  description: `最多${FORM_FIELD_TEXTAREA_MAX_LENGTH}字`,
  textarea: `最多${FORM_FIELD_TEXTAREA_MAX_LENGTH}字`,
  number: '请输入数字',
  customerAddress: '请选择客户地址',
  relationCustomer: '由客户信息查询',
  relationProduct: '由产品信息查询',
  user: '请选择人员',
  date: '日期',
  datetime: '日期 + 时间',
  select: '请选择',
  location: '请输入',
  phone: '请输入电话号码',
  code: '请通过移动端扫码或手动输入',
  serialNumber: '请输入'
};

/**
 * @description 获取默认的占位符
 * ! 目前特殊处理的是 maxlength 最大长度
 * @returns {String} 占位符
 */
export function getDefaultPlaceholder(formType = '', maxlength) {
  if (isNumber(maxlength)) {
    return `最多${maxlength}字`;
  }

  return DEFAULT_PLACEHOLDER[formType] || '';
}

/**
 * 将设计器输出的字段格式转换成后端可接受的类型
 * 注意： 需要在提交时补全以下字段，如果有的话：
 *  tableName、templateId、templateName
 */
export function toField(fields, module, typeId, isClone = true) {
  
  const fieldList = cloneDeep(fields)
  
  return fieldList.map((field, index) => {
    
    let formType = field.formType
    const fieldConfig = FormFieldMap.get(formType)
    
    if (fieldConfig && isFunction(fieldConfig.packFunction)) {
      fieldConfig.packFunction(field)
    }
    
    return FormField.toField(field, index, module, typeId, isClone)
  });
}

/** 将后端字段转换成设计器可接受的字段 */
export function toFormField(fields) {
  return migration(fields).map(item => FormField.fromField(item));
}

/** 迁移旧有字段至新类型，主要用于兼容客户、产品旧字段 */
export function migration(fields) {
  return fields.map(field => {
    // 多选格式调整
    if (field.formType == 'selectMulti') {
      if (!field.setting) field.setting = { isMulti: true, dataSource: [] };
      field.formType = 'select';
      field.setting.isMulti = true;
    }

    return field;
  });
}

/** 是否为多选类型 */
export function isMultiSelect(field) {
  let setting = field.setting || {};

  return (
    (field.formType == 'select' && setting.isMulti) ||
    field.formType == 'selectMulti'
  );
}

/** 是否为多级菜单类型 */
export function isCascader(field) {
  let setting = field.setting || {};

  return field.formType == 'cascader' && JSON.stringify(setting) == '{}';
}

/** 是否为单选类型 */
export function isSelect(field) {
  let setting = field.setting || {};

  return (
    (field.formType == 'select' && !setting.isMulti) ||
    field.formType == 'level' ||
    field.formType == 'serviceContent' ||
    field.formType == 'serviceType'
  );
}

/** 是否为日期类型 yyyy-MM-dd */
export function isDate(field) {
  let setting = field.setting;

  return (
    field.formType == 'date' ||
    (field.formType == 'planTime' &&
      setting != null &&
      setting.dateType == 'date')
  );
}

/** 是否为日期时间类型 yyyy-MM-dd HH:mm:ss */
export function isDatetime(field) {
  let setting = field.setting;

  return (
    field.formType == 'datetime' ||
    (field.formType == 'planTime' &&
      (setting == null || setting.dateType != 'date'))
  );
}

/** 是否为说明信息类型 */
export function isInfo(field) {
  return field.formType === 'info';
}

/** 构建placeholder */
export function genPlaceholder(field, defaultText = '') {
  let text = '';
  if (field.isNull == 0) {
    text += isSelect(field) || isMultiSelect(field) ? '[必选] ' : '[必填] ';
  }

  let placeholder = field.placeholder || field.placeHolder;
  if (placeholder) return text + placeholder;

  let key = field.formType;
  if (isDate(field)) key = 'date';
  if (isDatetime(field)) key = 'datetime';
  if (isSelect(field) || isMultiSelect(field) || field.formType == 'cascader')
    key = 'select';

  return text + (getDefaultPlaceholder(key, field?.maxlength) || '');
}

/**
 * 初始化所有字段的初始值
 * @param {*} fields 字段
 * @param {*} origin 原始值
 * @param {*} target 待合并的值
 */
export function initializeSetting(fields:any = []) {
  fields
    .forEach(field => {
      let formType = field.formType
      const fieldConfig = FormFieldMap.get(formType)
      
      if (fieldConfig && isFunction(fieldConfig.unPackFunction)) {
        fieldConfig.unPackFunction(field)
      }
      
    })
  
  return fields
}

/**
 * 检测是否为隐藏字段
 * @param {*} field - 待检测的字段
 * @param {*} form - 表单值
 * @param {*} allFields - 所有字段
 * @param {string} isSmooth - 是否平整。 值为true时，直接从form对象上取值；值为false时，根据字段isSystem取值
 */
export function isHiddenField(field, form, allFields, isSmooth = true) {
  let map = {};

  for (let i = 0; i < allFields.length; i++) {
    map[allFields[i].fieldName] = allFields[i];
  }

  return _isHiddenField(field, form, map, isSmooth);
}

export function _isHiddenField(field, form, fieldMap, isSmooth) {
  let setting = field.setting || {};
  let dependencies = setting.dependencies;
  // 无依赖不隐藏
  if (null == dependencies || Object.keys(dependencies).length == 0)
    return false;

  for (let prop in dependencies) {
    // 先判定依赖字段是否显示
    let depField = fieldMap[prop];
    if (depField == null) return true;
    if (_isHiddenField(depField, form, fieldMap, isSmooth)) return true;

    let val = getHiddenFieldValue(prop, form, fieldMap, isSmooth);
    let dep = dependencies[prop];
    if (Array.isArray(dep) && dep.length > 0 && dep.indexOf(val) >= 0)
      return false;
  }

  return true;
}

function getHiddenFieldValue(prop, form, fieldMap, isSmooth) {
  let field = fieldMap[prop];
  return getValue(field, form, isSmooth);
}

/**
 * 根据字段取值
 * @param {*} field - 字段
 * @param {*} form - 表单对象
 * @param {*} isSmooth - 是否平整。 值为true时，直接从form对象上取值；值为false时，根据字段isSystem取值
 */
export function getValue(field, form, isSmooth = false) {
  if (null == field) return null;
  let fieldName = field.fieldName;

  // 直接从form上取值，适用于FormBuilder
  if (isSmooth) return form[fieldName];

  // 客户负责人
  if (field.tableName == 'customer' && fieldName == 'manager') {
    return {
      userId: form.customerManager,
      displayName: form.customerManagerName
    };
  }

  // 产品负责人
  if (field.tableName == 'product' && fieldName == 'productManager') {
    return {
      userId: form.productManager,
      displayName: form.productManagerName
    };
  }

  // 系统字段
  if (field.isSystem == 1) return form[fieldName];

  // 自定义字段
  let attribute = form.attribute || {};
  return attribute[fieldName];
}

/**
 * 获取与当前字段同级的字段列表
 * @param {*} field - 当前字段
 * @param {*} fields - 表单字段
 */
export function getSameLevelFields(field, fields) {
  let sameLevelFields = [];
  
  let sameField = fields.find(f => f.fieldName == field.fieldName);
  
  // 在当前层级
  if (sameField) {
    sameLevelFields = fields;
  } else {
    fields.forEach(f => {
      if (sameLevelFields.length) return; // 已找到
      
      if (f?.subFormFieldList?.length) {
        sameLevelFields = getSameLevelFields(field, f.subFormFieldList);
      }
    });
  }

  return sameLevelFields;
}

/**
 * 查找字段
 * @param {*} fields - 表单字段
 * @param {*} fieldName - 当前字段fieldName
 */
export function getSameField(fields, fieldName) {
  let sameField = fields.find(f => f.fieldName == fieldName);

  if (!sameField) {
    fields.forEach(field => {
      if (sameField) return;

      if (field?.subFormFieldList?.length) {
        sameField = getSameField(field.subFormFieldList, fieldName);
      }
    });
  }
  
  return sameField;
}



export function getSetting(setting) {
  try {
    return JSON.parse(setting) || {}
  } catch (error) {
    return setting
  }
}